using System;
using System.IO;
using System.Linq;
using System.Xml.Linq;

namespace MidnightPeach.Engine.Components
{
    public static class Utility
    {
        public static byte[] ReadBinaryFile(string path)
        {
            FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
            BinaryReader reader = new BinaryReader(stream);

            var buffer = new byte[stream.Length];
            reader.Read(buffer, 0, buffer.Length);

            reader.Close();
            stream.Close();

            return buffer;
        }

        public static bool IsValueType(this string typeString)
        {
            if (typeString == "System.Data.Linq.Binary")
                return false;

            if (typeString == "System.Xml.Linq.XElement")
                return false;

            Type type = Type.GetType(typeString);
            return type.IsValueType;
        }

        public static bool AddUpdateCheckAttribute(string dbmlFilePath)
        {
            XNamespace nameSpace = "http://schemas.microsoft.com/linqtosql/dbml/2007";

            XElement root = XElement.Load(dbmlFilePath);
            var tableElements = root.Elements(nameSpace + "Table");

            foreach (var tableElement in tableElements)
            {
                var typeElement = tableElement.Element(nameSpace + "Type");

                var columnElements = typeElement.Elements(nameSpace + "Column");

                if (columnElements.Any(x => x.Attribute("IsVersion") != null))
                    continue;

                foreach (var columnElement in columnElements)
                    columnElement.SetAttributeValue("UpdateCheck", "Never");
            }

            try
            {
                root.Save(dbmlFilePath);

                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
